package com.midnight.rstar.config;

import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.env.Environment;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.util.HashMap;
import java.util.Map;

@Component
public class GlobalConfig {
    @Autowired
    private Environment env;
    public static String FILE_NAME =  "demo.json";
    private Map<String, Map<String,String>> globalJsonMap;
    private final ObjectMapper objectMapper;

    @Autowired
    public GlobalConfig(ObjectMapper objectMapper) {
        this.objectMapper = objectMapper;
    }

    @PostConstruct
    public void init() {
        File file = new File(env.getProperty("root_path"),FILE_NAME);
        if (file.exists()) {
            try {
                String jsonContent = new String(Files.readAllBytes(file.toPath()));
                globalJsonMap = objectMapper.readValue(jsonContent, new TypeReference<Map<String, Map<String,String>>>() {});
                System.out.println("Global JSON Map: " + globalJsonMap);
            } catch (IOException e) {
                e.printStackTrace();
            }
        } else {
            System.out.println("File does not exist: " + file.getAbsolutePath());
        }
        if(globalJsonMap==null){
            globalJsonMap = new HashMap<>();
        }
    }

    public Map<String, Map<String,String>> getGlobalJsonMap() {
        return globalJsonMap;
    }

    private File configFile;
    public File getConfigFile() {
        if(configFile==null){
            configFile = new File(env.getProperty("root_path"),FILE_NAME);
        }
        return configFile;
    }
}